package com.slixils.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slixils.demo.exception.GlobalException;
import com.slixils.demo.mapper.UserMapper;
import com.slixils.demo.pojo.entity.User;
import com.slixils.demo.service.UserService;
import com.slixils.demo.utils.CookieUtil;
import com.slixils.demo.utils.UUIDUtil;
import com.slixils.demo.vo.LoginVo;
import com.slixils.demo.vo.RespBean;
import com.slixils.demo.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: JinChongLi
 * @Description:
 * @Date: Created in 21:08 2022/4/5
 * @Modified By:
 */
@Service
public class UserServicelmpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public RespBean login(LoginVo loginVo ,HttpServletRequest request, HttpServletResponse response) {
        String username = loginVo.getMobile();//手机号
        String password = loginVo.getPassword();
//        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password))
//            return RespBean.error(RespBeanEnum.LOGINVO_ERROR);
//        if(!ValidatorUtil.isMobile(username))
//            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        User user = userMapper.selectById(username);
        if (user == null) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //生成Cookie
        String userTicket = UUIDUtil.uuid();
        //将用户信息存入redis
       redisTemplate.opsForValue().set("user:" + userTicket, user);

       // request.getSession().setAttribute(userTicket, user);
      CookieUtil.setCookie(request, response, "userTicket", userTicket);
        return RespBean.success(userTicket);
    }
    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(userTicket)) {
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        if (user != null) {
            CookieUtil.setCookie(request, response, "userTicket", userTicket);
        }
        return user;
    }
}
